package com.it.controller;

import com.it.pojo.ClOrder;
import com.it.pojo.ClShoppingCar;
import com.it.pojo.LinkFoodCart;
import com.it.service.ClOrderService;
import com.it.service.ClShoppingCarService;
import com.it.service.LinkFoodCartService;
import com.it.utils.ResultData;
import com.mysql.cj.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @Controller
 *   作用1： 将当前对象的创建交给spring管理
 *   作用2：作为控制层代码的标识
 */
@Controller
public class ClOrderController {

	@Autowired    //自动注入(由spring创建当前对象并为属性赋值)
	private ClOrderService clOrderService;

	@Autowired	//自动注入(由spring创建当前对象并为属性赋值)
	private ClShoppingCarService clShoppingCarService;

	@Autowired    //自动注入(由spring创建当前对象并为属性赋值)
	private LinkFoodCartService linkFoodCartService;

	/** 1.查询所有订单信息 */
	@RequestMapping("/clOrderList")
	public String clOrderList(Model model, HttpServletRequest request, HttpServletResponse response){
		try{
			HttpSession session = request.getSession();
			String userId = session.getAttribute("loginUserId").toString();
			String cartId = request.getParameter("cartId");

			//调用service层的findAll方法，查询所有的订单信息
			List<ClOrder> list = clOrderService.findByUserIdAndCartId(userId, cartId);

			//将所有订单信息的list集合存入model中，带到JSP显示
			model.addAttribute("list", list);
		}catch (RuntimeException re){
			re.printStackTrace();
		}

		return "cl/order/list";
	}

	/** 4.根据id修改订单信息
	 *  4.1.先根据id查询当前订单的信息 */
	@RequestMapping("/clOrderInfo")
	public String sysOrderInfo(HttpServletRequest request, String id, Model model){
		if(StringUtils.isNullOrEmpty(id)){
			id = request.getParameter("id");
		}
		//1.根据id查询订单信息
		ClOrder clOrder = clOrderService.findById(id);

		//2.将订单信息存入model中(存入request域中)
		model.addAttribute("order", clOrder);
		//3.转向clOrder_update.jsp
		return "cl/order/update";
	}

	/**
	 * **************************************************** 订单流程 ************************************************************
	 */
	/**
	 * 5.1、下单
	 * 5.2、出单
	 * 5.3、成单
	 * 5.4、退单
	 * 5.5、消单
	 */

	/**
	 * 5.1、下单
	 * 新建一个order
	 */
	@RequestMapping("/cl/update/ordertime")
	@ResponseBody
	public ResultData<ClOrder> updateOrdertime(HttpServletRequest request){
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		HttpSession session = request.getSession();
		ResultData<ClOrder> resultData = new ResultData<ClOrder>();
		/**
		 * 查询购物车并修改下单时间为当前时间
		 * 把订单里购物车页面所展示的所有信息都写入order实体的content里
		 * 并把订单的ordertime置为当前时间
		 */
		try {
			String cartId = request.getParameter("cartId");

			ClShoppingCar cart = clShoppingCarService.findById(cartId);
			Date now = new Date();
			cart.setLastTimeOrder(now);
			int i = clShoppingCarService.updateById(cart);
			if (i > 0) {
				List<LinkFoodCart> linkList = linkFoodCartService.findByCartId(cartId);
				cart.setLinkFoodCarts(linkList);

				ClOrder clOrder = new ClOrder();
				clOrder.setId(UUID.randomUUID().toString().substring(0, 32));

				clOrder.setCartId(cartId);
				StringBuffer content = new StringBuffer();
				content.append("总价：" + cart.getFoodPriceTotal() + "。");
				content.append("总数：" + cart.getFoodCountTotal() + "。");
				content.append("下单时间：：" + sdf.format(cart.getLastTimeOrder())+ "。");
				for(LinkFoodCart link : cart.getLinkFoodCarts()){
					content.append("菜品："+link.getFoodName() + "，");
					content.append("份数："+link.getPerAmount() + "，");
					content.append("单价："+link.getPerPrice() + "，");
					content.append("价格："+link.getTotalPerPrice() + "。");
				}
				clOrder.setContent(content.toString());

				String userId = session.getAttribute("loginUserId").toString();
				clOrder.setUserId(userId);
				String userName = session.getAttribute("loginUserName").toString();
				clOrder.setUserName(userName);

				String diningPlaceType = request.getParameter("diningPlaceType").toString();
				clOrder.setDiningPlaceType(Integer.parseInt(diningPlaceType));

				String receiverAddress = request.getParameter("receiverAddress").toString();
				clOrder.setReceiverAddress(receiverAddress);
				String receiverName = request.getParameter("receiverName").toString();
				clOrder.setReceiverName(receiverName);
				String receiverMobile = request.getParameter("receiverMobile").toString();
				clOrder.setReceiverMobile(receiverMobile);
				String receiverRemark = request.getParameter("receiverRemark").toString();
				clOrder.setReceiverRemark(receiverRemark);

				clOrder.setCreateTime(now);
				clOrder.setOrderTime(now);  // 取消支付流程的功能展示，所以ordertime和createtime一样

				clOrder.setStatus(0);

				i = clOrderService.addClOrder(clOrder);
				if (i > 0) {
					resultData.setData(clOrder);
					resultData.setSuccess(true);
					resultData.setMsg("下单成功！");
					resultData.setCode(200);
				} else {
					resultData.setSuccess(false);
					resultData.setMsg("下单失败！");
					resultData.setCode(500);
				}
			} else {
				resultData.setSuccess(false);
				resultData.setMsg("数据异常，下单失败！");
				resultData.setCode(500);
			}
		}catch(RuntimeException re){
			re.printStackTrace();
			resultData.setSuccess(false);
			resultData.setMsg("系统异常，下单失败！");
			resultData.setCode(500);
		}
		return resultData;
	}

	/**
	 * 5.1、成单
	 */
	@RequestMapping("/cl/update/finishtime")
	public String updateFinishtime(String orderId){
		ClOrder order = clOrderService.findById(orderId);
		order.setStatus(2);
		order.setFinishTime(new Date());
		try{
			clOrderService.updateById(order);
		}catch(RuntimeException re){
			re.printStackTrace();
		}
		return "redirect:/clOrderList";
	}

	/**
	 * 5.2、退单
	 */
	@RequestMapping("/cl/update/backtime")
	public String updateBacktime(String orderId){
		ClOrder order = clOrderService.findById(orderId);
		order.setStatus(-1);
		order.setBackTime(new Date());
		try{
			clOrderService.updateById(order);
		}catch(RuntimeException re){
			re.printStackTrace();
		}
		return "redirect:/clOrderList";
	}

}
